import { BadRequestException, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { User } from '../entities/user.entity'
import { sendCode } from '../utils'
import { JwtService } from '@nestjs/jwt'

@Injectable()
export class UserService {
  // private readonly【仅读的】
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}

  /**
   * 发送短信
   * @param phone
   */
  async sendCode(phone: string) {
    const user: User = await this.findOne({ phone: phone })
    // user:{} user:{id:1}  ture[得到的user为空对象，或者有值时，为ture]
    // user:undefined false[的到user为undefined则为false]
    // console.log(user);undefined
    if (user) {
      throw new BadRequestException('手机号已注册')
    } else {
      return sendCode(phone)
    }
  }

  /**
   * 查询用户
   * @param where
   */
  findOne(where) {
    return this.userRepository.findOne({ where })
  }

  /**
   * 注册
   * @param body
   */
  async register(body: User) {
    const { id } = await this.userRepository.save(body)
    return id ? '注册成功' : '注册失败'
  }

  /**
   * 登录
   * @param phone
   * @param password
   */
  async login({ phone, password }) {
    const user = await this.userRepository.findOne({ where: { phone } })
    if (!user) throw new BadRequestException('手机号码不正确')
    if (user.password !== password) throw new BadRequestException('密码不正确')
    // 颁发token
    const token = this.jwtService.sign({ id: user.id, phone: user.phone })
    delete user.password
    return { user, token }
  }

  /**
   * 修改
   * @param body
   * @param id
   */
  async edit(body: User, id) {
    // console.log(body)//null prototype【没有原型】
    const user = {}
    for (const key in body) {
      user[key] = body[key]
    }
    const { affected } = await this.userRepository.update(id, user)
    return affected ? '修改成功' : '修改失败'
  }
}
